package com.itheima.job;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ArrayUtil;
import com.itheima.domain.mongo.Movement;
import com.itheima.domain.mongo.RecommendMovement;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Set;

@Component
public class MovementRecommendTask {

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    MongoTemplate mongoTemplate;

    @Scheduled(cron = "0 0/1 * * * ?")
    public void movementRecommend(){
        System.out.println("动态推荐开始更新");

        //1.获取redis中所有推荐的用户key(集合)
        Set<String> keySet = stringRedisTemplate.keys("MOVEMENTS_RECOMMEND_*");

        System.out.println(keySet);

        //2.遍历集合,获取推荐给每个用户的动态pid字符串
        if (CollUtil.isNotEmpty(keySet)) {
            for (String key : keySet) {
                //3.删除推荐给当前用户的所有动态
                //3.1 获取用户的id
                Long userId = Long.parseLong(key.replace("MOVEMENTS_RECOMMEND_",""));

                //3.2 删除推荐动态
                mongoTemplate.remove(new Query(Criteria.where("userId").is(userId)), RecommendMovement.class);

                String pidStr = stringRedisTemplate.opsForValue().get(key);

                //4.切分pid字符串获取pid数组
                String[] pidArr = pidStr.split(",");

                //5.遍历pid数组,获取每个pid对应的movement
                if (ArrayUtil.isNotEmpty(pidArr)) {
                    for (String pid : pidArr) {
                        Movement movement = mongoTemplate.findOne(new Query(Criteria.where("pid").is(Long.valueOf(pid))), Movement.class);

                        //6.封装推荐动态,存入动态推荐表中
                        RecommendMovement recommendMovement = new RecommendMovement();
                        recommendMovement.setCreated(movement.getCreated());
                        recommendMovement.setUserId(userId);
                        recommendMovement.setPid(Long.valueOf(pid));
                        recommendMovement.setPublishId(movement.getId());
                        recommendMovement.setScore(90D);

                        mongoTemplate.save(recommendMovement);
                    }
                }
            }
        }
        System.out.println("推荐动态结束~~");
    }
}
